<template>
    <div class="app-container">
      <el-form :model="queryParams" class="frominfo" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <div class="from-item">
          <el-form-item label="微信名称" prop="wcUserName">
            <el-input v-model="queryParams.wcUserName" @keyup.enter.native="handleQuery" placeholder="请输入微信名称" clearable/>
          </el-form-item>
          <el-form-item label="所属人员" v-if="!common" prop="userName">
            <el-input v-model="queryParams.userName" @keyup.enter.native="handleQuery" placeholder="请输入所属人员" clearable/>
          </el-form-item>
          <el-form-item label="在群助手" prop="wcName" v-if="!common">
            <!-- <el-input v-model="queryParams.wcName" @keyup.enter.native="handleQuery" placeholder="请输入在群助手" clearable/> -->
            <el-select style="width: 120px;" v-if="!qommon"
                       v-model="queryParams.deptId"
                       @change="getDept"
                       placeholder="请选择区域"
                       clearable
            >
              <el-option
                v-for="dict in deptName"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <el-autocomplete style="width: 160px;"
                             class="my-autocomplete"
                             v-model="param.lable"
                             :fetch-suggestions="querySearch"
                             placeholder="请输入内容"
                             @select="handleSelect"
            ></el-autocomplete>
            <!-- <el-select
              v-model="queryParams.wcId"
              placeholder="请选择助手"
              clearable
            >
              <el-option
                v-for="dict in userName"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> -->
          </el-form-item>
          <el-form-item label="标签" prop="labelName">
            <el-select v-model="labelName" multiple placeholder="请选择标签">
              <el-option
                v-for="item in friendInfo"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictLabel">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否去重" prop="dis"  v-if="!qommon">
            <el-select v-model="queryParams.isDistinct" clearable>
              <el-option label="不去重" value="0">不去重</el-option>
              <el-option label="去重" value="1">去重</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择状态" v-show="show" prop="liveControlState">
            <el-select v-model="queryParams.liveControlState" placeholder="请选择" clearable>
              <el-option v-for="dict in control" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </div>
        <div class="from-Btn">
          <el-form-item>
              <el-button class="blue-button" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
      <el-table v-loading="loading" row-key="id" ref="friendTable" :data="wcFriendInfoList" :header-cell-style="{ background: '#fcfcfd', color: '#000' }" @selection-change="handleSelectionChange"  @select-all="handleSelectAll" :border="false">
        <el-table-column label="全选" type="selection" :reserve-selection="true" width="55" align="center" :show-overflow-tooltip="true"/>
        <el-table-column label="微信名称" prop="wcUserName" align="center" :show-overflow-tooltip="true"/>
        <el-table-column label="最近任务时间" prop="lastDeatisDate" align="center" :show-overflow-tooltip="true"/>
        <el-table-column label="微信备注" prop="wcNoteName" align="center" :show-overflow-tooltip="true"/>
        <el-table-column label="是否在网" prop="interState" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_network_status" :value="scope.row.interState"/>
          </template>
        </el-table-column>
        <el-table-column label="好友标签" prop="friendLabel" align="center" :show-overflow-tooltip="true"/>
        <el-table-column label="区域" prop="deptName" align="center" :show-overflow-tooltip="true"/>
        <el-table-column label="微信所属人员" prop="nickName" align="center" :show-overflow-tooltip="true"/>
      </el-table>

      <pagination v-show="total>0" style="height: 50px;margin-bottom: 0;" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
      <div class="line">
          <div class="line-reset"><i class="el-icon-refresh-left"></i><span>清空</span></div>
          <span>已选{{ ids.length }}</span>
      </div>
      <div class="app-box" v-if="show">
        <div class="app-btn" @click="submitAdd">确认添加</div>
      </div>
    </div>
  </template>

  <script>
  import request from '@/utils/request'
  import { listDept } from "@/api/system/dept";
  import { listWcUser } from "@/api/system/user";
  export default {
    name: "WcFriendInfo",
    dicts: ['sys_network_status'],
    props:{
      show: {
        type: Boolean,
        default: true,
      },
      checkedIds: {
        type: Array,
        default: [],
      },
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        idsTwo:[],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        selectAll:false,
        selection:[],
        chatTime:[],
        // 微信好友信息表格数据
        wcFriendInfoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        param:{
          wcId: null,
          lable:null,
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          wcId: null,
          wcUserName: null,
          userName: null,
          lableName: null,
          liveControlState: null,
          isDistinct: null,
        },
        labelName:[],
        deptName:[],
        control:[{label:'未选',value:0},{label:'已选',value:1}],
        common:false,
        qommon:false,
        form:{labelId:null,dataId:null,type:'group_label'},
        friendInfo:[],
        lableInfo:[],
        userParams: {
          pageNum: 1,
          pageSize: 9999,
          deptId: undefined,
        },
      };
    },
    created() {
      if (this.$store.state.user.roles.includes("common")) {
        this.common = true;
        this.qommon=true;
      }
      if (this.$store.state.user.roles.includes("qxleader")) {
        this.common = false;
        this.qommon=true;
      }
      if(!this.qommon){
        var deptName=[]
        listDept().then(response => {
          if(response.code==200){
            response.data.forEach((item) =>{
              deptName.push({value:item.deptId,label:item.deptName})
            })
            this.deptName=deptName
          }
        });
      }else{
        var userName=[]
        this.userParams=null
        listWcAssist(this.userParams).then((res) => {
          if (res["success"]) {
            const dt = res["data"];
            dt["records"].forEach((element) => {
              //userName.push({value:element.wcId,label:element.wcName})
              userName.push({value:element.wcName,label:element.wcId})
            });
          }
          this.userName=userName
        });
      }
    },
    watch:{
      checkedIds: {
        handler(newValue,oldValue){
          this.init()
        },
        deep: true
      }
    },
    mounted(){
      if(this.$store.state.user.roles.includes("common")){
        this.common=true
      }
      if(this.show){
        this.queryParams.liveControlState=0
      }else{
        this.queryParams.liveControlState=null
      }
      this.getList();
      this.friendLabel()
    },
    methods: {
      getDept(value) {
        if(value!=''){
          this.userParams.deptId=value
          this.queryParams.wcId=null
          var userName=[]
          listWcUser(this.userParams).then((res) => {
            //console.log(res)
            if (res["code"]==200) {
              const dt = res["rows"];
              dt.forEach((element) => {
                if(this.userParams.deptId==100){
                  if(element.deptId==100&&element.wcId!=''&&element.wcId!=null){
                    // userName.push({value:element.wcId,label:element.nickName})
                    userName.push({value:element.nickName,label:element.wcId})
                  }
                }else if(element.wcId!=''&&element.wcId!=null){
                  // userName.push({value:element.wcId,label:element.nickName})
                  userName.push({value:element.nickName,label:element.wcId})
                }
              });
            }
            this.userName=userName
          });
        }
      },
      handleSelect(item) {
        this.param.lable=item.value
        this.param.wcId=item.label
        this.queryParams.wcId=item.label
      },
      querySearch(queryString, cb) {
        var restaurants = this.userName;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      init(){
        //console.log(this.checkedIds)
        this.idsTwo=this.checkedIds
      },
      /** 查询微信好友信息列表 */
      getList() {
        this.loading = true;
        var lable=""
        if(this.labelName!=null){
          this.labelName.forEach(element => {
            lable+=","+element
          })
        }
        this.queryParams.friendLabel=lable.substring(1)
        listWcFriendInfo(this.queryParams).then(res => {
          if (res['code']==200) {
            const dt = res['data'];
            this.total = dt['total'];
            this.wcFriendInfoList = dt['records'];
            this.getSelection()
          }
          this.loading = false;
        });
        //console.log(this.ids)
        setTimeout(()=>{
          this.loading = false;
        },2000)
      },
      submitAdd(){
        const id =  this.ids
        //console.log(id)
        if(id!=''&&id!=null){
          updateWcFriendInfo({"ids":id,"liveControlState": 1}).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
            this.$emit("addSelect",true)
          });
        }else{
          this.$message({
              message: '请选择要添加的好友！',
              type: 'warning'
          });
        }
      },
      friendLabel(){
        friendLabel().then(res => {
          //console.log(res)
          if(res.code==200){
            this.friendInfo=res.data
          }
        });
      },
      handleUpdate(){
        if(this.ids!=''){
          this.open = true;
        }else{
          this.$message({
              message: '请选择！',
              type: 'warning'
          });
        }
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.beginTime=null
        this.queryParams.endTime=null
        if(this.chatTime!=''&&this.chatTime!=null){
          this.queryParams.beginTime=this.chatTime[0]+' 00:00:00'
          this.queryParams.endTime=this.chatTime[1]+' 23:59:59'
        }
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.chatTime=[]
        this.labelName=[]
        this.queryParams.friendLabel=null
        this.queryParams.deptId=''
        this.param.lable=''
        this.queryParams.wcId=""
        this.queryParams.isDistinct=""
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.$emit("changeSelect",selection)
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
      },
      handleSelectAll(selection){
        this.ids=selection.map(item => item.id)
        this.single = selection.length!==1
      },
      //复选框回选
      getSelection() {
        //console.log(this.idsTwo)
        return this.wcFriendInfoList.map(item => ({
          ...item,
          _checked: this.idsTwo.includes(item.id)
        }));
      }
    }
  };



  /** js请求 调用 */

  // 查询微信好友信息列表
  export function listWcFriendInfo(query) {
    return request({
      url: '/arbit/wcfriend_info/page',
      method: 'get',
      params: query
    })
  }

  // 修改微信好友信息
  export function updateWcFriendInfo(data) {
    return request({
      url: '/arbit/wcuser_info/UpFriendInfoLiveState',
      method: 'POST',
      data: data
    })
  }
  //获取所有好友标签
  export function friendLabel() {
    return request({
      url: '/label/relevance/type/friend_label',
      method: 'GET',
    })
  }
  </script>
  <style scoped lang="scss">
    .app-container{
      background-color: #f6f9fb;
      overflow-y: scroll;
      width: 90%;
    }
    .el-table::before{
        content: "";
        position: absolute;
        background-color: #ffffff00;
        z-index: 1;
    }
    .frominfo{
      display: flex;background-color: #fff;padding: 10px;padding-bottom: 0; margin-bottom: 20px;
      .from-item{
        display: flex;flex-wrap: wrap;
      }
      .from-Btn{
        display: flex;flex-direction: column;align-items: center;justify-content: center;width: 20%;
      }
    }
    .mb8{
      margin-bottom: 20px;
    }
    .blue-button {
      color: #fff;
      background-color: #0078fb !important;
      border-color: #0078fb !important;
    }
    .dia-box{
        padding: 20px;
        display: flex;
        flex-direction: column;
      .dia-box-search{
        display: flex;
        align-items: center;
        margin-bottom: 10px;
      }
      .dia-box-lable{
        width:90%;
        border-radius: 5px;
        border:1px solid #eee;
        min-height: 100px;
        display: flex;
        flex-wrap: wrap;
        padding: 10px;
        margin-bottom: 20px;
        .lable-box{
          padding: 0 5px;
          height: 20px;
          line-height: 20px;
          margin-right: 10px;
          border: 1px solid #dcdcdc;
          background-color: #ebf4ff;
          font-size: 12px;
          border-radius: 3px;
        }
        .select{
          color: #fff;
          background-color: #4095e5;
        }
      }
    }
    .dialog-footer{
      display: flex;
      justify-content: center;
    }
    .line{
      display: flex;
      align-items: center;
      background-color: #fff;
      font-size: 13px;
      padding: 0 0 15px 20px;
      .line-reset{
        background-color: #efefef;
        height: 25px;
        line-height: 25px;
        padding: 0 15px;
        border-radius: 5px;
        margin-right: 10px;
      }
    }
    .app-box{
        display: flex;
        align-items: center;
        justify-content: center;
        height: 60px;
        margin: 15px 0;
        background: #fff;
        .app-btn{
            width: 100px;
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #fff;
            text-align: center;
            background-color: #0078fb;
            border-radius: 5px;
        }
    }
    ::v-deep .el-table::before{
      background-color: transparent !important;
    }
  </style>
